<template>
  <div class="p-2">
    <el-card shadow="never" v-show="showSearch">
      <el-form
        :model="queryParamsBO"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="queryParamsBO.title"
            placeholder="请输入课程名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="展示日期" prop="sendTime">
          <el-date-picker
            v-model="queryParamsBO.sendTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="Pick a day"
            size="default"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >查询</el-button
          >

          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 按钮区 -->
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Edit"
              @click="handleAdd()"
              v-hasPermi="['system:user:edit']"
              >新增文章</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              v-hasPermi="['system:user:import']"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo:export']">导出</el-button>
            </el-col> -->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="ArticList"
          ></right-toolbar>
        </el-row>
      </template>

      <el-table :data="ArticList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="知识名称"
          align="center"
          prop="title"
          v-if="true"
        />

        <el-table-column label="创建者" align="center" prop="createBy" />

        <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="发布时间" align="center" prop="sendTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParamsBO.pageNum"
        v-model:limit="queryParamsBO.pageSize"
        @pagination="ArticList"
      />
    </el-card>

    <el-dialog
      v-model="dialogStatus.visible"
      :title="dialogStatus.title"
      width="80%"
      center
      append-to-body
      :show-close="true"
      @close="closeDialog"
    >
      <el-form
        :model="queryParamsBO"
        ref="diologFormRef"
        :inline="true"
        label-width="70px"
        class="dialogForm"
      >
        <el-form-item label="知识标题" prop="name">
          <el-input
            v-model="queryParamsBO.title"
            placeholder="请输入"
            clearable
            style="width: 220px"
          />
        </el-form-item>

        <el-form-item label="文章类别" prop="introduction">
          <el-select
            v-model="queryParamsBO.siteType"
            clearable
            placeholder="场景分类"
            style="width: 220px"
            @change="handelSenceChange"
          >
            <el-option
              v-for="item in selectArr.siteTypeArr"
              :key="(item as any).value"
              :label="(item as any).label"
              :value="(item as any).value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细类别" prop="introduction">
          <el-select
            v-model="queryParamsBO.articleType"
            clearable
            placeholder="详细类别"
            style="width: 220px"
          >
            <el-option
              v-for="item in selectArr.articleTypeArr"
              :key="(item as any).value"
              :label="(item as any).label"
              :value="(item as any).value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶" prop="introduction">
          <el-select
            v-model="queryParamsBO.isTop"
            clearable
            placeholder="详细类别"
            style="width: 220px"
          >
            <el-option
              v-for="item in selectArr.isTopArr"
              :key="(item as any).value"
              :label="(item as any).label"
              :value="(item as any).value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新闻封面">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed"
            :on-change="handChange"
            ref="coverUpload"
          >
            <el-icon v-show="upload"><Plus /></el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleUpload1()"
                  >
                    <el-icon><Download /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogStatus.preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="文章介绍" prop="introduction">
          <el-input
            v-model="queryParamsBO.introduction"
            maxlength="256"
            placeholder="Please input"
            rows="4"
            type="textarea"
            style="width: 500px"
          />
        </el-form-item>

        <el-form-item label="页面内容" prop="status" width="1000">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <editor
              style="height: 500px; overflow-y: hidden"
              v-model="queryParamsBO.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>

        <el-form-item class="innerDialogFooter">
          <el-button type="primary" icon="Search" @click="dialogSubmit"
            >提交</el-button
          >
          <el-button icon="Refresh" @click="closeDialog">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElButton, ElForm } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  getOssAuth as getOssAuthApi,
  postToOSS as postToOSSApi,
  addArtic as addArticApi,
  getArticList as getArticListApi,
  articDetail as articDetailApi,
  editArtic as editArticApi,
  delArtic as delArticApi
} from "@/service/api/school/substation";

import type { UploadFile } from "element-plus";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const handleCreated = (editor: any) => {
  editorRef.value = editor;
  console.log("created", editor);
};
// 内容 HTML
const toolbarConfig = {};
// 配置editor
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: {},
    },
  },
};
// 知识列表
const ArticList = ref([]);
const total = ref(0);
const diologFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
// 获取凭证BO
const getOssAuthBO = reactive({
  originalFileName: "",
});
// 上传图片到OSSBO
const initUploadImgBO = {
  OSSAccessKeyId: "",
  callback: "",
  expire: "",
  host: "",
  policy: "",
  signature: "",
  key: "",
};
// 获取知识列表BO
const initQueryParams = {
  id: "",
  status: "",
  pageSize: 10,
  pageNum: 1,
  title: "",
  sendTime: "",
  content: "",
  cover: "",
  introduction: "",
  isTop: false,
  siteType: "",
  articleType: "",
  url:'',
  isRich: false
};
const initDialogStatus = {
  preview:false,
  visible: false,
  title: "",
};
//
const BO = reactive({
  uploadImgBO: { ...initUploadImgBO },
  queryParamsBO: { ...initQueryParams },
  dialogStatus: { ...initDialogStatus },
});
const { uploadImgBO, queryParamsBO, dialogStatus } = toRefs(BO);

// 选择框
const selectArr = ref({
  siteTypeArr: [
    {
      value: "1",
      label: "家校共育",
    },
    {
      value: "2",
      label: "家校动态",
    },
  ],
  articleTypeArr: [],
  isTopArr: [
    {
      value: true,
      label: "是",
    },
    {
      value: false,
      label: "否",
    },
  ],
});

// 获取知识列表
const getArticList = async () => {
  let res = await getArticListApi(queryParamsBO.value);
  ArticList.value = res.rows;
  total.value = Number(res.total);
};
// 设置状态
const statusType = (status: string) => {
  switch (status) {
    case "正常":
      return "success";
    case "未确认":
      return "warning";
    case "禁言":
      return "danger";
    case "停用":
      return "info";
    default:
      return "";
  }
};
const single = ref(true);
const ids = ref([]);
const multiple = ref(true);
const showSearch = ref(true);

// 选中文章分类后
const handelSenceChange = (val: any) => {
  console.log(val);
  if (val === "1") {
    (selectArr.value.articleTypeArr as any) = [
      {
        value: "1",
        label: "理念介绍",
      },
      {
        value: "2",
        label: "政策解读",
      },
    ];
  } else {
    (selectArr.value.articleTypeArr as any) = [
      {
        value: "1",
        label: "热点新闻",
      },
      {
        value: "2",
        label: "共育活动",
      },
    ];
  }
};

// upload ref
const coverUpload = ref()
// 上传的文件
const uploadFile = ref()
// 展示图片
const dialogImageUrl = ref("");
// 是否上传封面
const isUploadCover = ref(false)

// 选择文件改变时调用
const handChange = (File: any) => {
  console.log(File);
  uploadFile.value = File;
};

// 封面图片上传
const handleUpload1 = async () => {
  getOssAuthBO.originalFileName = (uploadFile.value as any).name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", uploadImgBO.value.key);
  formData.append("OSSAccessKeyId", uploadImgBO.value.OSSAccessKeyId);
  formData.append("policy", uploadImgBO.value.policy);
  formData.append("signature", uploadImgBO.value.signature);
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", uploadImgBO.value.callback);
  formData.append("file", uploadFile.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    if (res.data.code === 200) {
      queryParamsBO.value.url = res.data.data.url
      console.log( queryParamsBO.value.url);
      isUploadCover.value = true
    }
    ElMessage({
      type: "success",
      message: "上传成功",
    });
  }
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogStatus.value.preview = true;
};

// 超出一个文件时调用
const handleExceed: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(uploadFile.value);
  coverUpload.value!.handleStart(uploadFile.value);
  // 清除文件
  coverUpload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  coverUpload.value!.handleStart(file);
};

// 新增文章
const addArtic = async () => {
  const res = await addArticApi(queryParamsBO.value)
  console.log(res);
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

// 获取每日知识详情
const articDetail = async (id: string) => {
  let res = await articDetailApi(id);
  console.log(res);
  queryParamsBO.value = res.data;
};
// 详情按钮
const handleDetail = async (row: any) => {
  await articDetail(row.id);
  dialogStatus.value.visible = true;
  if(queryParamsBO.value.siteType == '1') {
    (selectArr.value.articleTypeArr as any) = [
      {
        value: "1",
        label: "理念介绍",
      },
      {
        value: "2",
        label: "政策解读",
      },
    ];
  } else if (queryParamsBO.value.siteType == '2') {
    (selectArr.value.articleTypeArr as any) = [
      {
        value: "1",
        label: "热点新闻",
      },
      {
        value: "2",
        label: "共育活动",
      },
    ];
  }
};
// 新增按钮
const handleAdd = () => {
  dialogStatus.value.title = "新增知识";
  dialogStatus.value.visible = true;
};
// 删除按钮
const handleDelete = async (row?: any) => {
  if (row) {
    // 单个删除
    const res = await delArticApi(row.id);
    console.log(res);
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    }
  } else {
    // 批量删除
    const res = await delArticApi(ids.value);
    console.log(res);
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    }
  }
  getArticList();
};
// 获取上传凭证
const getOssAuth = async () => {
  const res = await getOssAuthApi(getOssAuthBO);
  uploadImgBO.value = res;
  console.log(res);
};

// 获取图片base64
const getBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgResult = reader.result;
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
};

// 上传到oss
const upload = async (file: File) => {
  getOssAuthBO.originalFileName = file.name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", uploadImgBO.value.key);
  formData.append("OSSAccessKeyId", uploadImgBO.value.OSSAccessKeyId);
  formData.append("policy", uploadImgBO.value.policy);
  formData.append("signature", uploadImgBO.value.signature);
  formData.append("callback", uploadImgBO.value.callback);
  formData.append("file", file); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  return res;
};

// 自定义上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义上传
  async customUpload(file: File, insertFn: any) {
    // file 即选中的文件
    // const res = await upload(file);
    // console.log(res);
    // if (res.data.code === 200) {
    //   // 自己实现上传，并得到图片 url alt href
    //   // 最后插入图片
    //   insertFn(res.data.data.url);
    // } else {
    //   ElMessage({
    //     type: "error",
    //     message: "失败",
    //   });
    // }
    const res = await getBase64(file);
    console.log(res);
    insertFn(res);
  },
};

// 关闭dialog
const closeDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
  queryParamsBO.value = Object.assign({}, initQueryParams);
};

// 提交按钮
const dialogSubmit = async () => {
  diologFormRef.value.validate(async (vilid: boolean) => {
    if (vilid) {
      if (queryParamsBO.value.id) {
        // 编辑
        const res = await editArticApi(queryParamsBO.value);
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "修改成功",
          });
        } else {
          ElMessage({
            type: "success",
            message: "修改失败",
          });
        }
      } else {
        // 新增
        const res = await addArtic();
        console.log(res);
      }
      queryParamsBO.value = Object.assign({},initQueryParams)
      getArticList()
      closeDialog();
    }
  });
};

// 新增富文本
const handleQuery = async () => {
  getArticList();
};

// 重置按钮
const resetQuery = () => {
  queryFormRef.value.resetFields();
  getArticList();
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 模拟 ajax 异步获取内容
onMounted(() => {
  getArticList();
});
</script>

<style scoped lang="scss">
.innerDialogFooter {
  margin: 0px 0 0 830px;
}
</style>
